<template>
  <div class="exam-container">
    <!-- 第一页面 start-->
    <div class="box_1">
      <div class="box_border">
        <el-descriptions title="组卷·基本数据" :column="2" border>
          <el-descriptions-item label="试卷名" label-align="right" :span="2">
            <el-input placeholder="在此输入试卷名" v-model="name"
          /></el-descriptions-item>

          <el-descriptions-item label="总分" label-align="right" :span="1">
            <el-input-number
              v-model="totalScore"
              :min="1"
              :max="1000"
              style="width: 99%"
              @change="handleChange_total"
            />
          </el-descriptions-item>

          <el-descriptions-item label="及格分" label-align="right" :span="1">
            <el-input-number
              v-model="passScore"
              :min="1"
              :max="1000"
              style="width: 99%"
              @change="handleChange_pass"
            />
          </el-descriptions-item>

          <el-descriptions-item label="标签" label-align="right" :span="2">
            <el-checkbox-group v-model="labels">
              <el-checkbox label="JAVA" name="label" />
              <el-checkbox label="NET" name="label" />
              <el-checkbox label="UI" name="label" />
              <el-checkbox label="TEST" name="label" />
              <el-checkbox label="WEB" name="label" />
            </el-checkbox-group>
          </el-descriptions-item>

          <el-descriptions-item label="描述" label-align="right" :span="2">
            <el-input v-model="explain" placeholder="试卷描述、可为空" type="textarea" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-button
        class="next_btn"
        type="primary"
        plain
        :disabled="name == '' || labels.length == 0"
        @click="next_btn"
        >下一步</el-button
      >
    </div>
    <!-- 第一页面 end-->

    <!-- 第二页面 start-->
    <div class="box_2">
      <div class="box_border">
        <el-descriptions title="组卷·选择试题" :column="2" border>
          <el-descriptions-item label="组卷方式" label-align="right" :span="1">
            <el-radio-group v-model="mode" @change="mode_handleChange">
              <el-radio label="1">人工</el-radio>
              <el-radio label="2">随机</el-radio>
            </el-radio-group>
          </el-descriptions-item>

          <el-descriptions-item label="题目数量" label-align="right" :span="1">
            <el-input-number
              v-model="topicNum"
              class="mx-4"
              :min="1"
              style="width: 99%"
              :max="100"
              controls-position="right"
              @change="topicNum_handleChange"
            />
          </el-descriptions-item>

          <el-descriptions-item label="难度" label-align="right" :span="1">
            <el-rate v-model="lv" :disabled="mode == 1" :max="10" />
          </el-descriptions-item>

          <el-descriptions-item label="操作" label-align="right" :span="1">
            <el-button plain type="primary" v-if="mode == 1" @click="personQuestion"
              >选择/替换 试题</el-button
            >
            <el-button plain type="primary" v-if="mode == 2" @click="randomQuestion"
              >随机出题</el-button
            >
          </el-descriptions-item>

          <el-descriptions-item label="已选试题" label-align="right" :span="2">
            <div style="height: 300px">
              <el-table :data="tableData" border height="300" style="width: 100%">
                <el-table-column label="序号" type="index" width="60px"></el-table-column>
                <el-table-column prop="content" label="题干" />
                <el-table-column prop="type" label="题型" width="180">
                  <template #default="scope">
                    <el-tag type="success" size="small">{{
                      scope.row.type == 1 ? '选择题' : '简答题'
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="labels" label="标签" width="180" />
                <el-table-column prop="lv" label="难度" width="180" />
              </el-table>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="current_page">
        <el-button class="prev_btn2" type="primary" plain @click="prev_btn2"> 上一步 </el-button>

        <el-button
          class="next_btn2"
          type="primary"
          plain
          :disabled="tableData.length == 0"
          @click="next_btn2"
          >下一步</el-button
        >
      </div>
    </div>
    <!-- 第二页面 end-->

    <!-- 第三页面 start-->
    <div class="box_3">
      <div class="box_border">
        <el-descriptions title="组卷·设置分数" :column="2" border>
          <template #extra>
            <!-- v-if="current_total==totalScore" -->
            <el-tag :type="ss"
              >当前已设置分数【{{ current_total }}】未设置分数【{{
                totalScore - current_total
              }}】</el-tag
            >
            <!-- <el-tag type="danger" v-else>当前已设置分数【{{current_total}}】未设置分数【{{totalScore-current_total }}】</el-tag> -->
            <!-- <el-tag v-if="current_total>totalScore" type="danger">当前已设置分数【{{ current_total }}】已超过【{{current_total-totalScore}}】</el-tag>
           <el-tag v-if="current_total<totalScore" type="danger">当前已设置分数【{{ current_total }}】还需设置【{{totalScore-current_total}}】</el-tag> -->
          </template>
          <el-descriptions-item label="分数设置" label-align="right" :span="2">
            <div style="height: 300px">
              <el-table :data="tableData" border height="300" style="width: 100%">
                <el-table-column label="序号" type="index" width="60px"></el-table-column>
                <el-table-column prop="content" label="题干" />
                <el-table-column prop="type" label="题型" width="180">
                  <template #default="scope">
                    <el-tag type="success" size="small">{{
                      scope.row.type == 1 ? '选择题' : '简答题'
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="labels" label="标签" width="180" />
                <el-table-column prop="lv" label="难度" width="180" />
                <el-table-column prop="labels" label="分数" width="240">
                  <template #default="scope">
                    <el-input-number
                      v-model="scope.row.score"
                      :min="1"
                      @change="score_handleChange"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="current_page">
        <el-button class="prev_btn2" type="primary" plain @click="prev_btn3"> 上一步 </el-button>

        <el-button
          class="next_btn2"
          type="primary"
          plain
          :disabled="totalScore != current_total"
          @click="next_btn3"
          >下一步</el-button
        >
      </div>
    </div>
    <!-- 第三页面 end-->

    <!-- 第四页面 start-->
    <div class="box_4">
      <div class="box_border">
        <el-descriptions title="组卷·最后确认" :column="3" border>
          <el-descriptions-item label="试卷名" label-align="right" :span="1">
            <el-tag>{{ name }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="标签" label-align="right" :span="1">
            <el-tag>{{ labels }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="难度" label-align="right" :span="1">
            <el-tag>{{ lv }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="总分" label-align="right" :span="1">
            <el-tag>{{ totalScore }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="及格分" label-align="right" :span="1">
            <el-tag>{{ passScore }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="题目数量" label-align="right" :span="1">
            <el-tag>{{ topicNum }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="已选试题" label-align="right" :span="2">
            <!-- <div style="height: 300px"> -->
            <!-- <el-table :data="tableData" border height="300" style="width: 100%">
                <el-table-column  type="index" width="60px"></el-table-column>
                <el-table-column prop="content"  />
                <el-table-column prop="type"  width="180">
                  <template #default="scope">
                    <el-tag type="success" size="small">{{
                      scope.row.type == 1 ? '选择题' : '简答题'
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="labels"  width="180" />
                <el-table-column prop="lv"  width="180" />
              </el-table> -->
            <div class="demo-collapse">
              <el-collapse accordion>
                <el-collapse-item :name="index" v-for="(item, index) in tableData" :key="index">
                  <template #title>
                    {{ index + 1 }}.{{ item.content }} &nbsp;<el-tag type="warning"
                      >{{ item.type == 1 ? '选择题' : '主观题' }}.{{ item.lv }}星</el-tag
                    >
                  </template>
                  <div></div>
                </el-collapse-item>
              </el-collapse>
            </div>

            <!-- </div> -->
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="current_page">
        <el-button class="prev_btn2" type="primary" plain @click="prev_btn4"> 上一步 </el-button>

        <el-button class="next_btn2" type="success" @click="complete_btn">完成</el-button>
      </div>
    </div>
    <!-- 第四页面 end-->
  </div>

  <!-- 抽取试题弹框 start-->
  <div>
    <div class="dialog_bigbox">
      <el-dialog v-model="dialogTableVisible" fullscreen title="抽取试题">
        <el-skeleton :loading="tisFirst" :rows="15" animated>
          <div class="dialog_box">
            <div class="header">
              <div>
                <div class="btn_import">
                  <el-button size="small" type="primary" @click="queryQuestionbanks" plain
                    >根据题库查询</el-button
                  >
                </div>

                <!-- 搜索框 -->
                <div class="mySearch_import">
                  <el-input
                    :width="150"
                    v-model="tKey"
                    placeholder="请输入你要查询的题干名称"
                    class="input-with-select"
                  >
                    <template #append>
                      <el-button :icon="Search" />
                    </template>
                  </el-input>
                </div>
              </div>
            </div>

            <div class="content_import">
              <el-table
                :data="tData"
                v-loading="tisLoad"
                :border="true"
                @selection-change="handleSelectionChange"
                :row-key="check_org"
              >
                <el-table-column label="复选框" type="selection" width="40px" :reserve-selection="true"></el-table-column>

                <el-table-column label="序号" type="index" width="60px"></el-table-column>
                <el-table-column
                  label="题干"
                  prop="content"
                  :show-overflow-tooltip="true"
                  class="last_commoner"
                >
                </el-table-column>
                <el-table-column label="类型" prop="type" width="100">
                  <template #default="scope">
                    <el-tag type="primary" size="small">
                      {{ scope.row.type == 1 ? '选择题' : '主观题' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="难度" prop="lv" width="60px"></el-table-column>

                <el-table-column
                  label="作者"
                  prop="author"
                  :show-overflow-tooltip="true"
                  width="100"
                ></el-table-column>

                <el-table-column
                  label="标签"
                  prop="labels"
                  :show-overflow-tooltip="true"
                  width="100"
                ></el-table-column>

                <el-table-column
                  label="添加时间"
                  prop="createTime"
                  :show-overflow-tooltip="true"
                ></el-table-column>
              </el-table>
              <el-tag size="small" type="info" style="margin: 10px 10px 0 0"
                >应该选择【{{ topicNum }}】道试题,实际选择【{{
                  select_orderId.length
                }}】道试题,否则不能确认选择</el-tag
              >
              <!-- 分页 -->
              <div
                style="
                  margin-top: 10px;
                  padding-bottom: 10px;
                  display: flex;
                  justify-content: space-between;
                  border: 1px solid #eee;
                "
              >
                <el-pagination
                  background
                  @size-change="tChangLimit"
                  layout="sizes,prev, pager, next,total"
                  :total="tTotal"
                  small
                  @current-change="changPage"
                  style="margin: 10px 0 0 10px"
                  v-model:current-page="tPage"
                  :page-sizes="[10, 20, 30, 40, 50]"
                />

                <el-button
                  type="primary"
                  style="margin-top: 10px; margin-right: 10px"
                  plain
                  @click="sureimport"
                  :disabled="select_orderId.length != topicNum"
                  >确认选择</el-button
                >
              </div>
            </div>
          </div>
        </el-skeleton>
      </el-dialog>
    </div>
  </div>
  <!-- 抽取试题弹框 end-->
</template>

<script lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, ref, watchEffect } from 'vue'
import { RandomQuestions, addTestPaper } from '@/api/testpaper'
import { queryAllQuestion } from '@/api/exam'
import { openLoad, closeLoad } from '@/utils/loading'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    const data = reactive<any>({
      /**
       * 试卷名
       */
      name: '',
      /**
       * 总分
       */
      totalScore: 100,
      /**
       * 及格分
       */
      passScore: 60,
      /**
       * 试题标签
       */
      labels: [],
      /**
       * 试卷描述
       */
      explain: '',
      /**
       * 组卷方式 单选按钮 1人工/2随机
       */
      mode: '1',
      before_mode: '1',
      /**
       * 题目数量
       */
      topicNum: 10,
      /**
       * 询问是否改变数量,存储topicNum之前的值
       */
      beforeTopicNum: 1,
      /**
       * 题目难度
       */
      lv: 1,
      ss: 'success',
      /**
       * 分配总分额度 第三页面使用
       */
      current_total: 0,
      /**
       * 第二个页面选择的题目的显示
       */
      tableData: [],
      /**
       * 选择的题目id,成绩
       */
      questions: [],
      /**
       * 第一个页面可见性
       */
      reveal_1: '',
      /**
       * 第二个页面可见性
       */
      reveal_2: 'none',
      /**
       * 第三个页面可见性
       */
      reveal_3: 'none',
      /**
       * 第四个页面可见性
       */
      reveal_4: 'none'
    })
    const router = useRouter()

    const tdata = reactive<any>({
      //弹出框状态
      dialogTableVisible: false,
      tisFirst: true,
      tisLoad: false,
      tIsBan: 0,
      tIsPublish: 1,
      tPage: 1,
      tTotal: 0,
      tLimit: 10,
      tData: [],
      selectionKeys: [],
      checkDataId: [], //表格select复选框的数据的id
      select_orderId: [], //表格select复选框的数据
      tKey: '',
      tLabels: '',
      tExcludeQBID: '',
      tBanks: '',
      tExcludeQIDs: [],
      tChapterids: ''
    })

    const events = {
      /**
       * 
       * @param row 数据回显row-key方法
       */
      check_org:(row:any)=>{
               return row.id;
      },
      score_handleChange: () => {
        let total = 0
        data.tableData.map((d: any) => (total += d.score))
        data.current_total = total
        if (data.totalScore - data.current_total != 0) {
          data.ss = 'danger'
        } else {
          data.ss = 'success'
        }
      },
      /**
       * 选中框选中事件
       * @param rows
       */
      handleSelectionChange(rows: any) {
        //弹出框复选框选中的id
        tdata.select_orderId = rows.map((item: any) => item)
        tdata.checkDataId = rows.map((item: any) => item.id)
      },

      /**
       * 人工出题选择试题按钮
       */
      personQuestion: () => {
        tdata.dialogTableVisible = true
        tdata.tisLoad = true
        queryAllQuestion({
          page: tdata.tPage,
          limit: tdata.tLimit,
          isPublish: tdata.tIsPublish,
          isBan: tdata.tIsBan,
          key: tdata.tKey,
          labels: tdata.tLabels,
          excludeQBID: tdata.tExcludeQBID,
          banks: tdata.tBanks,
          excludeQIDs: tdata.excludeQIDs,
          chapterids: tdata.tChapterids
        }).then((res: any) => {
          tdata.tData = res.data.data
          tdata.tTotal = res.data.total
          setTimeout(() => {
            tdata.tisFirst = false
          }, 1000)
          tdata.tisLoad = false
        })
      },

      /**
       * 选择试题后确认按钮点击事件
       */
      sureimport: () => {
        ElMessageBox.confirm(`确认选择这${tdata.select_orderId.length}道题目吗？`)
          .then(() => {
            tdata.dialogTableVisible = false
            data.tableData = tdata.select_orderId
            console.log(data.tableData)
            tdata.tPage = 1
            tdata.tLimit = 10
          })
          .catch(() => {})
      },

      /**
       * 抽取试题修改每页显示多少条信息
       */
      tChangLimit(val: any) {
        tdata.tLimit = val
      },

      /**
       * 随机出题按钮点击事件
       */
      randomQuestion: () => {
        let minlv: number = data.lv - 1 == 0 ? 2 : data.lv
        let maxlv: number = data.lv > 10 ? 10 : data.lv
        openLoad('请稍后')
        setTimeout(() => {
          closeLoad()
        }, 1000)
        RandomQuestions({
          count: data.topicNum,
          minLv: (minlv - 1) * data.topicNum,
          maxLv: maxlv * data.topicNum
        }).then((res: any) => {
          if (res.result == 0) {
            data.tableData = res.data.data
            ElMessage.success(res.message)
          } else {
            ElMessage.error(res.message)
          }
        })
      },

      /**
       * 选题方式改变事件
       */
      mode_handleChange: () => {
        ElMessageBox.confirm('更改组卷方式会清空已选试题,确认继续吗？')
          .then(() => {
            data.before_mode = data.mode
            data.lv = 1
            data.tableData = []
          })
          .catch((res: any) => {
            data.mode = data.before_mode
          })
      },
      /**
       * 题目数量改变事件
       */
      topicNum_handleChange: () => {
        ElMessageBox.confirm('更改题目数量会清空已选试题,确认继续吗？')
          .then((res: any) => {
            data.beforeTopicNum = data.topicNum
            data.tableData = []
          })
          .catch((res: any) => {
            data.topicNum = data.beforeTopicNum
          })
      },
      /**
       * 组卷完成按钮事件
       */
      complete_btn: () => {
        let exam_labels = data.labels.split(',')
        data.questions = data.tableData.map((d: any) => {
          return { id: d.id, score: d.score }
        })
        ElMessageBox.confirm('确认要新增试卷吗')
          .then((res: any) => {
            openLoad('请稍后')
            addTestPaper({
              count: data.topicNum,
              explain: data.explain,
              isCheck: data.mode == '1' ? 0 : 1,
              labels: exam_labels,
              lv: data.lv,
              mode: data.mode,
              name: data.name,
              passScore: data.passScore,
              questions: data.questions,
              totalScore: data.totalScore
            }).then((res: any) => {
              closeLoad()
              if (res.result === 0) {
                ElMessage.success(res.message)
                router.go(-1)
              } else {
                ElMessage.success(res.message)
              }
            })
          })
          .catch(() => {})
      },
      /**
       * 第四页 最后一页上一步事件
       */
      prev_btn4: () => {
        data.reveal_4 = 'none'
        data.reveal_3 = ''
        data.labels = data.labels.split(',')
        console.log(data.labels)
      },

      /**
       * 第三个页面上一步
       */
      prev_btn3: () => {
        data.reveal_3 = 'none'
        data.reveal_2 = ''
      },

      /**
       * 第三个页面下一步
       */
      next_btn3: () => {
        data.reveal_3 = 'none'
        data.reveal_4 = ''
        console.log(data.tableData, 'kkkk')
        data.labels = data.labels.join(',')
        console.log(data.labels)
      },
      /**
       * 第二个页面上一步
       */
      prev_btn2: () => {
        data.reveal_2 = 'none'
        data.reveal_1 = ''
      },
      /**
       * 第二个页面下一步
       */
      next_btn2: () => {
        // 将分数赋值给数组 取平均分 余分赋值给最后一题
        data.tableData.forEach((d: any, i: number) => {
          if (data.totalScore % data.topicNum == 0) {
            d.score = data.totalScore / data.topicNum
            data.questions.push(d)
          } else {
            let avg: number = parseInt(data.totalScore / data.topicNum) //平均分数
            if (i == data.tableData.length - 1) {
              //将多余分数分配给最后一个
              d.score = avg + (data.totalScore % data.topicNum)
            } else {
              d.score = avg
            }
          }
          data.current_total = data.totalScore
        })
        console.log(data.tableData)

        data.reveal_2 = 'none'
        data.reveal_3 = ''
      },
      /**
       * 第一个页面下一步
       */
      next_btn: () => {
        data.reveal_1 = 'none'
        data.reveal_2 = ''
      },

      /**
       *
       * @param val 及格分改变事件
       */
      handleChange_pass: (val: any) => {
        data.passScore = val
      },

      /**
       *
       * @param val 总分改变事件
       */
      handleChange_total: (val: any) => {
        data.totalScore = val
      }
    }

    watchEffect(() => {
      //抽取试题弹窗
      if (tdata.dialogTableVisible == true) {
        // tdata.select_orderId = []
        events.personQuestion()
      }
      if (tdata.dialogTableVisible == false) {
        tdata.tPage = 1
        tdata.tLimit = 10
        tdata.tisFirst = true
      }
    })

    return {
      ...toRefs(data),
      ...events,
      ...toRefs(tdata),
      Search
    }
  }
})
</script>


<style scoped>
.box_border {
  margin: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 6px;
  position: relative;
}

.next_btn {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 94%;
}

/* .next_btn2{
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 94%;
} */

.prev_btn2 {
  margin-top: 5px;
  margin-bottom: 5px;
  margin-left: 84%;
}

.box_1 {
  display: v-bind(reveal_1);
}

.box_2 {
  display: v-bind(reveal_2);
}

.box_3 {
  display: v-bind(reveal_3);
}

.box_4 {
  display: v-bind(reveal_4);
}

.question-head {
  border: 1px solid #eee;
  padding: 5px;
}

.dialog_box {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #eee;
  border-radius: 6px;
}

.header {
  margin: 10px;
  border: 1px solid #eee;
  height: 50px;
  line-height: 44px;
  border-radius: 6px;
}

.mySearch_import {
  width: 400px;
  margin: auto;
}

.btn_import {
  float: left;
  margin-left: 10px;
}

.content_import {
  margin: 10px;
}
</style>